import { defineStore } from "pinia"
import { CourseProgressReport, CourseProgressQuery, CourseProgressInfo } from "@/models/course"
import { courseApi } from "@/services"
import { toast } from "vue3-toastify"

const useCourseStore  = defineStore('Course', {
    // state
    state:() =>({
        courseDetailObject: {} as any,
        courseProgress: '',
        playAuthObject: {} as any,
        courseProgressList: [] as CourseProgressInfo[],
    }),
    // actions
    actions:{
        // 获取课程详情（JSONObject）
        async getCourseDetail(srcCourseId:string) {
            try{
                const res = await courseApi.getCourseDetail(srcCourseId)
                this.courseDetailObject = JSON.parse(res.detail)
                this.courseProgress = res.progress
            } catch(err) {
                toast.error('获取课程详情出现异常：'+ err);
            }
        },
        // 上报课程进度
        async reportProgress(srcCourseId: string, seq: string, playSecond: number) {
            try{        
                const data : CourseProgressReport = {
                    srcCourseId: srcCourseId,
                    seq: seq,
                    playSecond: playSecond,
                }
                const res = await courseApi.reportProgress(data)
                return res ? res.result : false
            } catch(err) {
                toast.error('上报课程进度出现异常：'+ err);
                return false;
            }
        },
        // 查询课程所有章节进度
        async queryProgress(srcCourseId: string) {
            try{        
                const data : CourseProgressQuery = {
                    srcCourseId: srcCourseId,
                }
                const res = await courseApi.queryProgress(data)
                this.courseProgressList = res ? res.result : [] as CourseProgressInfo[]
            } catch(err) {
                toast.error('查询课程所有章节进度出现异常：'+ err);
            }
        },
        // 授权播放
        async getPlayAuth(vid:string) {
            try{
                const res = await courseApi.getPlayAuth(vid)
                this.playAuthObject = JSON.parse(res.detail)
            } catch(err) {
                toast.error('授权播放出现异常：'+ err);
            }
        },
    },
    getters:{
        courseDetail:(state) => state.courseDetailObject,
        playAuth:(state) => state.playAuthObject,
        isLearning:(state) => state.courseProgress && state.courseProgress!='0%',
    }
})

export default useCourseStore